package com.bosssoft.boss_exam_web.common.annotation.support;


import com.bosssoft.boss_exam_core.common.config.security.ApplicantJwtTokenHelper;
import com.bosssoft.boss_exam_db.entity.Applicant;
import com.bosssoft.boss_exam_web.common.annotation.LoginApplicant;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;


@Component
public class LoginApplicantHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        //如果参数使用了@LoginApplicant注解并且参数的数据类型为String，则返回true,支持该参数
        return parameter.getParameterType().isAssignableFrom(String.class) && parameter.hasParameterAnnotation(LoginApplicant.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer container,
                                  NativeWebRequest request, WebDataBinderFactory factory) throws Exception {
        //通过http请求头LOGIN_TOKEN_KEY对应的token值来判断该token是否存在，如果存在则获取出该token对应的用户id，赋值给参数
        System.err.println("================================================");
        String token = request.getHeader(ApplicantJwtTokenHelper.AUTH_HEADER_NAME);
        System.err.println("接受的到token：  " + token);
        if (token == null || token.isEmpty()) {
            return null;
        }
        Applicant applicant = new ApplicantJwtTokenHelper().parse(token);
        if(applicant==null){
            return null;
        }else {
            return  applicant.getId();
        }
    }
}
